package data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import exceptions.IdentifierException;
import exceptions.DataException;
/**
 * A Data generator that generates data from data inputting.
 * Should be used by other Data Generators.
 * @author poet
 *
 */
public class DataGatherer implements DataStorage, DataConstructor{
	private Map<Integer, Player> players;
	private Set<Game> games;
	private Map<Player,List<Game>> playersToGamesMap;
	public DataGatherer(){
		players = new HashMap<Integer,Player>();
		games = new HashSet<Game>();
		playersToGamesMap = new HashMap<Player,List<Game>>();
	}
	public Player [] getPlayers(){
		return players.values().toArray(new Player [players.size()]);
	}
	public Game [] getGames(){
		return games.toArray(new Game [games.size()]);
	}
	public Map<Player, List<Game>> getPlayersToGamesMap() {
		return playersToGamesMap;
	}
	/**
	 * Will only create the player if it doesn't already exist.
	 * Judges if player exists based on ID.
	 * @throws MissingDataException if playerName is null or only white spaces.
	 * @throws IdentifierException Will not happen, as if ID exists, will return the player.
	 */
	public Player addPlayer(String playerName, int playerID) throws DataException, IdentifierException{
		if (!players.containsKey(playerID))
			players.put(playerID, new Player(playerName, playerID));
		Player ret = players.get(playerID);
		if (!ret.getPlayerName().equals(playerName))
			throw new DataException("Player name does not match ID", DataGatherer.class.getName());
		return ret;
	}
	/**
	 * Returns player by id.
	 */
	public Player getPlayerByID(int id){
		return players.get(id);
	}
	/**
	 * Prevents duplicates
	 */
	public void addGame(Game game){
		if (games.contains(game))
			return;
		games.add(game);
		addGameToPlayerMap(game);
	}
	private void addGameToPlayerMap(Game game){
		addGameToPlayerMap(game.getPlayer1(), game);
		addGameToPlayerMap(game.getPlayer2(), game);
	}
	private void addGameToPlayerMap(Player player, Game game){
		List<Game> gamesVSOpponent = playersToGamesMap.get(player);
		if (gamesVSOpponent == null){
			gamesVSOpponent = new ArrayList<Game>();
			playersToGamesMap.put(player, gamesVSOpponent);
		}
		gamesVSOpponent.add(game);
	}
	@Override
	public DataConstructor getDataConstructor() {
		return this;
	}
	@Override
	public DataStorage getDataStorage() {
		return this;
	}

	
}
